package com.crm.system.controller.cluePoolManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.crm.common.model.DataResponse;
import com.crm.common.model.DhPageInfo;
import com.crm.common.model.DhResponse;
import com.crm.common.model.Enum.ResponseCodeEnum;
import com.crm.common.util.ESUtil;
import com.crm.model.entity.cluePoolManager.ClueFollow;
import com.crm.model.qo.cluePoolManager.ClueFollowQO;
import com.crm.model.qo.cluePoolManager.CustomerOnlineFollowQO;
import com.crm.model.vo.cluePoolManager.ClueFollowContractVO;
import com.crm.model.vo.cluePoolManager.ClueFollowVO;
import com.crm.model.vo.cluePoolManager.ImportFollowVO;
import com.crm.system.service.cluePoolManager.ClueFollowService;
import com.crm.system.service.cluePoolManager.ExcelUtil;
import com.github.pagehelper.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * @author wll
 * info 线索/客户跟进
 */
@RestController
@RequestMapping("/clueFollow")
@Slf4j
public class ClueFollowController {

    @Value("${esurl}")
    public String ESurl;

    @Autowired
    private ClueFollowService clueFollowService;

    /**
     * @param clueFollowQO 跟进参数
     * @return
     * @author wll
     * info 用户模块-我的线索池-线索清单-添加跟进 / 用户模块-客户管理-我的客户-跟进
     */
    @PostMapping("/addClueFollow")
    public DataResponse addClueFollow(HttpServletRequest request,
                                      @RequestBody ClueFollowQO clueFollowQO) {
        try {
            String result = clueFollowService.addClueFollow(clueFollowQO);
            if (!StringUtils.isBlank(result)) {
                return new DhResponse(ResponseCodeEnum.OK.getResponseCode(), result);
            }
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        } catch (Exception e) {
            log.error("clueFollow addClueFollow error:" , e);
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        }
    }

    /**
     * @Description:根据客户id获取线索跟进记录
     * @Param: customerId 客户id
     * @Author: luojie
     * @Date: 2021/3/15 18:53
     */
    @GetMapping("/selectClueFollowListByCustomerId")
    public DataResponse selectClueFollowListByCustomerId(@RequestParam("customerId") String customerId) {
        try {
            List<ClueFollowContractVO> clueFollowContractVOList = clueFollowService.selectClueFollowListByCustomerId(customerId);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(), clueFollowContractVOList);
        } catch (Exception e) {
            log.error("clueFollow selectClueFollowListByCustomerId error:" , e);
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * @Description:跟进记录
     * @Param:
     * @Author: chaifuyou
     * @Date: 2021/4/2 9:18
     */
    @GetMapping("/selectClueFollowList")
    public DataResponse selectClueFollowList(@RequestParam(value = "pageIndex") Integer pageIndex,
                                             @RequestParam(value = "pageSize") Integer pageSize,
                                             @RequestParam(value = "sort" , required = false) String sort,
                                             @RequestParam(value = "sortOrder" , required = false) String sortOrder,
                                             ClueFollowQO clueFollowQO) {
        try {
            DhPageInfo<ClueFollowVO> clueFollowContractVOList = clueFollowService.selectClueFollowList(clueFollowQO, pageIndex, pageSize, sort, sortOrder);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(), clueFollowContractVOList);
        } catch (Exception e) {
            log.error("clueFollow selectClueFollowListByCustomerId error:" , e);
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }


    /**
     * 获取通话录音
     *
     * @param followId
     * @return
     * @Author renshaorong
     * @Date 2021/8/23
     */
    @PostMapping("/getCallRecord")
    public DataResponse getCallRecord(String followId) {
        if (StringUtil.isEmpty(followId)) {
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(), clueFollowService.getCallRecord(followId));
    }

    /**
     * 图表数据获取
     *
     * @param dateUnit---本周1/本月2/上月3
     * @param startTimeStr           开始日期
     * @param endTimeStr             结束日期
     * @return
     * @Author renshaorong
     * @Date 2021/4/12
     */
    @PostMapping("selectClueFollowChartVOList")
    public DataResponse selectClueFollowChartVOList(@RequestParam(value = "dateUnit") Integer dateUnit,
                                                    @RequestParam(value = "startTimeStr" , required = false) String startTimeStr,
                                                    @RequestParam(value = "endTimeStr" , required = false) String endTimeStr) {
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(), clueFollowService.selectClueFollowChartVOList(dateUnit, startTimeStr, endTimeStr));
    }

    /**
     * 图表数据获取
     */
    @PostMapping("selectAdminClueFollowChartVOList")
    public DataResponse selectAdminClueFollowChartVOList(
            @RequestParam(value = "startTimeStr" , required = false) String startTimeStr,
            @RequestParam(value = "endTimeStr" , required = false) String endTimeStr) {
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(), clueFollowService.selectAdminClueFollowChartVOList(startTimeStr, endTimeStr));
    }

    /**
     * 折线图数据获取
     *
     * @param dateUnit---本周1/本月2/上月3
     * @param startTimeStr           开始日期
     * @param endTimeStr             结束日期
     * @return
     * @Author renshaorong
     * @Date 2021/4/13
     */
    @PostMapping("getPolyLine")
    public DataResponse getPolyLine(@RequestParam(value = "dateUnit") Integer dateUnit,
                                    @RequestParam(value = "startTimeStr" , required = false) String startTimeStr,
                                    @RequestParam(value = "endTimeStr" , required = false) String endTimeStr) {
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(), clueFollowService.getPolyLine(dateUnit, startTimeStr, endTimeStr));
    }

    /**
     * 折线图数据获取
     *
     * @param startTimeStr 开始日期
     * @param endTimeStr   结束日期
     * @return
     * @Author renshaorong
     * @Date 2021/4/13
     */
    @PostMapping("getAdminPolyLine")
    public DataResponse getAdminPolyLine(@RequestParam(value = "startTimeStr" , required = false) String startTimeStr,
                                         @RequestParam(value = "endTimeStr" , required = false) String endTimeStr) {
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(), clueFollowService.getAdminPolyLine(startTimeStr, endTimeStr));
    }

    /**
     * 总跟进次数饼状图数据获取
     *
     * @param dateUnit---本周1/本月2/上月3
     * @param startTimeStr           开始日期
     * @param endTimeStr             结束日期
     * @return
     * @Author renshaorong
     * @Date 2021/4/14
     */
    @PostMapping("getNumPieData")
    public DataResponse getNumPieData(@RequestParam(value = "dateUnit") Integer dateUnit,
                                      @RequestParam(value = "startTimeStr" , required = false) String startTimeStr,
                                      @RequestParam(value = "endTimeStr" , required = false) String endTimeStr) {
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(), clueFollowService.getNumPieData(dateUnit, startTimeStr, endTimeStr));
    }

    /**
     * 总跟进次数饼状图数据获取
     *
     * @param ---本周1/本月2/上月3
     * @param startTimeStr           开始日期
     * @param endTimeStr             结束日期
     * @return
     * @Author renshaorong
     * @Date 2021/4/14
     */
    @PostMapping("getAdminNumPieData")
    public DataResponse getAdminNumPieData(
            @RequestParam(value = "startTimeStr" , required = false) String startTimeStr,
            @RequestParam(value = "endTimeStr" , required = false) String endTimeStr) {
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(), clueFollowService.getAdminNumPieData(startTimeStr, endTimeStr));
    }

    /**
     * 获取商机状态饼状图数据
     *
     * @param dateUnit
     * @param startTimeStr
     * @param endTimeStr
     * @param type         跟进类型
     * @return
     * @Author renshaorong
     * @Date 2021/4/14
     */
    @PostMapping("getBusinessStatusData")
    public DataResponse getBusinessStatusData(@RequestParam(value = "dateUnit") Integer dateUnit,
                                              @RequestParam(value = "type") Integer type,
                                              @RequestParam(value = "startTimeStr" , required = false) String startTimeStr,
                                              @RequestParam(value = "endTimeStr" , required = false) String endTimeStr) {
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(), clueFollowService.getBusinessStatusData(dateUnit, startTimeStr, endTimeStr, type));
    }

    /**
     * 获取过程状态饼状图数据
     *
     * @param dateUnit
     * @param startTimeStr
     * @param endTimeStr
     * @return
     * @Author renshaorong
     * @Date 2021/4/14
     */
    @PostMapping("getProcessStatusData")
    public DataResponse getProcessStatusData(@RequestParam(value = "dateUnit") Integer dateUnit,
                                             @RequestParam(value = "type") Integer type,
                                             @RequestParam(value = "startTimeStr" , required = false) String startTimeStr,
                                             @RequestParam(value = "endTimeStr" , required = false) String endTimeStr) {
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(), clueFollowService.getProcessStatusData(dateUnit, startTimeStr, endTimeStr, type));
    }

    /**
     * 获取过程状态饼状图数据
     *
     */
    @PostMapping("getAdminProcessStatusData")
    public DataResponse getAdminProcessStatusData(
            @RequestParam(value = "type") Integer type,
            @RequestParam(value = "startTimeStr" , required = false) String startTimeStr,
            @RequestParam(value = "endTimeStr" , required = false) String endTimeStr) {
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(), clueFollowService.getAdminProcessStatusData(startTimeStr, endTimeStr, type));
    }

    /**
     * 客户线上跟进
     *
     * @param request
     * @param customerOnlineFollowQO -线上跟进参数
     * @return {@link {com.crm.common.model.DataResponse}}
     * @Author pym
     * @Date 2021/4/15 8:55
     */
    @PostMapping("/customerOnlineFollowUp")
    public DataResponse customerOnlineFollowUp(HttpServletRequest request,
                                               @RequestBody CustomerOnlineFollowQO customerOnlineFollowQO) {
        try {
            String result = clueFollowService.customerOnlineFollowUp(customerOnlineFollowQO);
            if (!StringUtils.isBlank(result)) {
                return new DhResponse(ResponseCodeEnum.OK.getResponseCode(), result);
            }
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        } catch (Exception e) {
            log.error("clueFollow customerOnlineFollowUp error:" , e);
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        }
    }

    /**
     * 一机多用(线上跟进之操作跟进记录表)
     *
     * @param customerOnlineFollowQO
     * @author yincuimei
     */
    @PostMapping("/oneMachineMultipleUses")
    public DataResponse oneMachineMultipleUses(@RequestBody CustomerOnlineFollowQO customerOnlineFollowQO) {
        try {
            String result = clueFollowService.oneMachineMultipleUses(customerOnlineFollowQO);
            if (!StringUtils.isBlank(result)) {
                return new DhResponse(ResponseCodeEnum.OK.getResponseCode(), result);
            }
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        } catch (Exception e) {
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        }
    }

    /**
     * 客户跟进详情关键字分词
     *
     * @param followId -跟进id
     * @Author chaifuyou
     * @Date 2021/5/20 16:29
     */
    @PostMapping("/followDetailParticiple")
    public DataResponse followDetailParticiple(@RequestParam String followId) {
        try {
            clueFollowService.followKeywordParticiple(followId);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
        } catch (Exception e) {
            log.error("clueFollow followDetailParticiple error:" , e);
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        }
    }


    /**
     * @Description: 跟进记录导入
     * @Param: [file]
     * @Return: com.crm.common.model.DataResponse
     * @Author: lixq-f
     * @Date: 2021/6/8
     **/
    @PostMapping("/importExcel")
    public DataResponse clueFollowImportExcel(@RequestParam("file") MultipartFile file) {
        clueFollowService.clueFollowImportExcel(file);
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
    }


    /**
     * @Description: 模板下载
     * @Param: [req, resp]
     * @Return: com.crm.common.model.DataResponse
     * @Author: lixq-f
     * @Date: 2021/6/8
     **/
    @GetMapping("/downTemplate")
    public DataResponse getExcelTemplate(HttpServletRequest req, HttpServletResponse resp) {
        clueFollowService.downTemplate(req, resp);
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
    }


    /**
     * 导入跟进记录
     *
     * @param request
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/importFollow")
    public DataResponse importFollow(HttpServletRequest request,
                                     @RequestParam MultipartFile file,
                                     @RequestParam String companyId
    ) throws IOException {
        JSONObject jsonObject = new JSONObject();
        try {
            ExcelUtil excelUtil = new ExcelUtil();
            List<ImportFollowVO> list = excelUtil.excelImport(file.getInputStream(), ImportFollowVO.class);//1.读取前端的excel文件并转换成list集合
            if (list == null || list.size() == 0) {
                return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
            }
            jsonObject = clueFollowService.importFollow(list, companyId);

        } catch (Exception e) {
            log.error("clueFollow importFollow:" , e);
        }
        //返回导入数量、重复数量
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(), jsonObject);
    }

    /**
     * 线上电话  跟进详情修改
     *
     * @param clueFollow 跟进记录
     *                   yincuimei合用用户系统-跟进记录-跟进详情页面-可修改跟进详情(备注:如有修改请联调测试这个功能)
     * @return
     */
    @PostMapping("/updateClueFollow")
    public DataResponse updateClueFollow(@RequestBody ClueFollow clueFollow) {
        Boolean result = clueFollowService.updateClueFollow(clueFollow);
        if (result) {
            ESUtil.syncFollow(clueFollow.getClueFollowId(),ESurl);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
        } else {
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        }
    }

    /**
     * 根据Excel同步数据库跟进类型为空的数据
     *
     * @param request
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/importFollow2")
    public DataResponse importFollow2(HttpServletRequest request,
                                      @RequestParam MultipartFile file,
                                      @RequestParam(required = false) String companyId
    ) throws IOException {
        JSONObject jsonObject = new JSONObject();
        try {
            ExcelUtil excelUtil = new ExcelUtil();
            List<ImportFollowVO> list = excelUtil.excelImport(file.getInputStream(), ImportFollowVO.class);//1.读取前端的excel文件并转换成list集合
            if (list == null || list.size() == 0) {
                return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
            }
            clueFollowService.importFollow2(list, companyId);

        } catch (Exception e) {
            log.error("clueFollow importFollow:" , e);
        }
        //返回导入数量、重复数量
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
    }

}
